package xin.mashibo.artcobutest.activity;

import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v7.app.AppCompatActivity;
import android.util.Log;
import android.widget.ArrayAdapter;
import android.widget.ListView;

import java.util.ArrayList;
import java.util.List;

import xin.mashibo.artcobutest.R;
import xin.mashibo.artcobutest.constant.ServiceConstant;
import xin.mashibo.artcobutest.vo.CardMac1About;

/**
 * @author MaShibo
 *         on 2018/3/21
 */
public class InitCreditActivity extends AppCompatActivity {

    private static final String TAG = "InitCreditActivity";

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.listview);
        setTitle(R.string.initCreditActivityTitle);
        ListView listView = findViewById(R.id.list_view);
        String infos = getIntent().getStringExtra(ServiceConstant.MAC1_KEY);
        ArrayAdapter<String> adapter = new ArrayAdapter<>(this, android.R.layout.simple_list_item_1, generateDataList(infos));
        listView.setAdapter(adapter);
    }

    /**
     * 生成MAC1相关数据列表
     *
     * @param infos MAC1相关数据
     * @return MAC1相关数据列表
     */
    private List<String> generateDataList(String infos) {
        CardMac1About infoObj = new CardMac1About(infos);
        List<String> dataList = new ArrayList<>();
        dataList.add("卡号：" + infoObj.getCardNo());
        dataList.add("卡余额：" + infoObj.getBalance());
        dataList.add("充值金额：" + infoObj.getIncMny());
        dataList.add("伪随机数：" + infoObj.getRandom());
        dataList.add("MAC1码：" + infoObj.getMac1());
        dataList.add("联机交易序号：" + infoObj.getOnlineSn());
        String tac = buildTac(infoObj);
        dataList.add("TAC：" + tac);
        Log.i(TAG, "TAC: " + tac);
        return dataList;
    }

    /**
     * 根据Mac1等信息构建Tac码
     *
     * @param extend mac1相关信息
     * @return tac
     */
    private String buildTac(CardMac1About extend) {
        StringBuilder tac = new StringBuilder();
        tac.append(extend.getBalance());
        while (tac.length() < 8) {
            tac.insert(0, '0');
        }
        tac.append(extend.getOnlineSn());
        tac.append("01");
        tac.append("00");
        tac.append(extend.getRandom());
        tac.append(extend.getMac1());
        return tac.toString();
    }

    /**
     * 启动改活动
     *
     * @param context 发起的活动
     * @param infos   MAC1信息组合
     */
    public static void actionStart(Context context, String infos) {
        Intent intent = new Intent(context, InitCreditActivity.class);
        intent.putExtra(ServiceConstant.MAC1_KEY, infos);
        context.startActivity(intent);
    }
}
